package com.damage.purchase_dept.web;

import com.damage.common.config.CodeConfig;
import com.damage.common.dto.OrderSender;
import com.damage.common.entity.Order;
import com.damage.common.exception.IdentityException;
import com.damage.common.exception.IncorrectStateException;
import com.damage.common.exception.ObsoleteException;
import com.damage.common.exception.RelateException;
import com.damage.common.oa.sendOrder.SendOrderWorkflowService;
import com.damage.common.object.BaseResp;
import com.damage.common.util.UserUtil;
import com.damage.purchase_dept.oa.sendOrder.StartSendOrderService;
import com.damage.purchase_dept.service.IOrderService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
@ResponseBody
@Slf4j
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private StartSendOrderService sendOrderService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private SendOrderWorkflowService workflowService;

    @PostMapping("/generate/{purhcasePlanId}")
    public BaseResp generateOrder(@PathVariable("purhcasePlanId")Integer purhcasePlanId){
        try {
            List<Order> orders = orderService.generateOrderByPurchasePlanId(purhcasePlanId);
            return BaseResp.ok(orders);
        } catch (IncorrectStateException | ObsoleteException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }

    @PostMapping("/send/{id}")
    public BaseResp sendOrder(@PathVariable("id") Integer orderId,OrderSender orderSender, HttpSession session){
        User user = UserUtil.getUserFromSession(session);
        if (user == null || Strings.isNullOrEmpty(user.getId())){
            //用户未登录
            return BaseResp.error(CodeConfig.ERROR_NOT_LOGIN);
        }
        if (!user.getFirstName().equals(orderSender.getSender())){
            return BaseResp.error("传入的发送人不是当前用户");
        }

        try {
            Order order = sendOrderService.startSendOrder(orderId, orderSender);
            return BaseResp.ok(order);
        } catch (IdentityException | RelateException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }

    }

    @GetMapping("/list/task")
    public BaseResp taskList(HttpSession session){
        String userId = UserUtil.getUserFromSession(session).getId();
        List<Order> orderList = workflowService.findTodoTasks(userId);
        return BaseResp.ok(orderList);
    }

    @GetMapping("/list/running")
    public BaseResp runnlingList(){
        List<Order> planList = workflowService.findRunningProcessInstaces();
        return BaseResp.ok(planList);
    }

    @GetMapping("/list/finished")
    public BaseResp finishedList(){
        List<Order> planList = workflowService.findFinishedProcessInstaces();
        return BaseResp.ok(planList);
    }

    @GetMapping("/comment/{id}")
    public BaseResp getCancelOrderComment(@PathVariable("id")Integer orderId){
        Order order = orderService.findById(orderId);
        String processInstanceId = order.getProcessInstanceId();
        List<Comment> commentList = taskService.getProcessInstanceComments(processInstanceId);
        List<String> fullMessageList = new ArrayList<>();
        for (Comment comment: commentList) {
            fullMessageList.add(comment.getFullMessage());
        }
        return BaseResp.ok(fullMessageList);
    }

    @PostMapping("/cancel/complete/{id}")
    public BaseResp completeCancelOrder(@PathVariable("id")String taskId){
        try {
            taskService.complete(taskId);
            return BaseResp.ok();
        } catch (Exception e) {
            log.error("完成任务失败，任务:{}",taskId);
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }

}
